#!/bin/bash

DIR_INPUT=/var/www/opencart/var/caricamento
DIR_BACKUP=$DIR_INPUT/bck
DIR_LOG=$DIR_INPUT/log

FIELDS_TERMINATED=';'
LINES_TERMINATED='\n'

USER_DB=root
PASSWORD_DB=renault
DB=opencart

exist_if_not_exist_input()
{
if [ ! -e $FILE_INPUT ]
then
    echo "" >> $FILE_LOG
    echo "Il file " $FILE_INPUT " non esiste " >> $FILE_LOG
    echo "" >> $FILE_LOG
    end_log
    exit 99
fi
}

start_mysql()
{
  DATA=`date`
  echo "" >> $FILE_LOG
  echo "Inizio caricamento dati da file in tabella [" $DATA "]" >> $FILE_LOG
}

end_mysql()
{
  DATA=`date`
  echo "" >> $FILE_LOG
  echo "Fine caricamento dati da file in tabella [" $DATA "]" >> $FILE_LOG
}

start_log()
{
  DATA=`date`
  echo "" >> $FILE_LOG
  echo "*****************************************" >> $FILE_LOG
  echo "Inizio elaborazione [" $DATA "]" >> $FILE_LOG
}

end_log()
{
  DATA=`date`
  echo "" >> $FILE_LOG
  echo "Fine elaborazione [" $DATA "]" >> $FILE_LOG
  echo "" >> $FILE_LOG
}

mysql_load()
{
  echo "mysql carico da " $FILE_INPUT >> $FILE_LOG
  echo "" >> $FILE_LOG

  mysql -u $USER_DB -p$PASSWORD_DB -e "LOAD DATA LOCAL INFILE '$FILE_INPUT' INTO TABLE $TABLE FIELDS TERMINATED BY '$FIELDS_TERMINATED' LINES TERMINATED BY '$LINES_TERMINATED' $FIELDS " $DB

  echo "Esito caricamento mysql " $? >> $FILE_LOG
}

backup()
{
  echo "" >> $FILE_LOG
  echo "Backup file input " >> $FILE_LOG
  mv $FILE_INPUT $DIR_BACKUP/.
}

elabora()
{
  start_log

  echo "Parametro in input '$1' " >> $FILE_LOG

  if [ "$1" = "" ] 
  then
    exist_if_not_exist_input

    start_mysql

    mysql_load

    end_mysql

    backup
  fi

  if [ -n "${SCRIPT_PHP+x}" ] 
  then
    ## echo SCRIPT_PHP is set
    php $SCRIPT_PHP $FILE_LOG
  fi

  end_log
}

